interface WeatherInfo {
  city: string;
  weather: string;
  temperature: string;
  humidity: string;
  winddirection: string;
  windpower: string;
  reporttime: string;
}

interface ForecastInfo {
  date: string;
  dayweather: string;
  nightweather: string;
  daytemp: string;
  nighttemp: string;
  daywind: string;
  nightwind: string;
  daypower: string;
  nightpower: string;
}

interface WeatherState {
  currentWeather: WeatherInfo | null;
  forecastWeather: ForecastInfo[];
  loading: boolean;
  error: string | null;
}

export const useWeather = () => {
  const state = reactive<WeatherState>({
    currentWeather: null,
    forecastWeather: [],
    loading: false,
    error: null
  });

  const searchCity = ref('');

  // 高德地图配置
  const AMAP_KEY = 'ea14acfbeff3ab37b1a0ac893135a7e8';

  // 获取天气图标
  const getWeatherIcon = (weather: string): string => {
    if (!weather) return 'fa-cloud';
    
    const weatherMap: { [key: string]: string } = {
      '晴': 'fa-sun-o',
      '多云': 'fa-cloud',
      '阴': 'fa-cloud',
      '小雨': 'fa-cloud-rain',
      '中雨': 'fa-cloud-rain',
      '大雨': 'fa-cloud-showers-heavy',
      '暴雨': 'fa-cloud-showers-heavy',
      '雷阵雨': 'fa-bolt',
      '雪': 'fa-snowflake-o',
      '雾': 'fa-smog',
      '霾': 'fa-smog'
    };
    
    for (const [key, icon] of Object.entries(weatherMap)) {
      if (weather.includes(key)) {
        return icon;
      }
    }
    return 'fa-cloud';
  };

  // 获取星期名称
  const getDayName = (dateStr: string): string => {
    if (!dateStr) return '未知';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '未知';
      const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return days[date.getDay()];
    } catch {
      return '未知';
    }
  };

  // 格式化日期
  const formatDate = (dateStr: string): string => {
    if (!dateStr) return '--';
    try {
      const date = new Date(dateStr);
      if (isNaN(date.getTime())) return '--';
      return `${date.getMonth() + 1}/${date.getDate()}`;
    } catch {
      return '--';
    }
  };

  // 搜索天气
  const searchWeather = async () => {
    debugger
    if (!searchCity.value.trim()) {
      state.error = '请输入城市名称';
      return;
    }
    
    await getWeatherByCity(searchCity.value.trim());
  };

  // 根据城市获取天气
  const getWeatherByCity = async (city: string) => {
    debugger
    state.loading = true;
    state.error = null;
    
    try {
      // 获取当前天气
      const currentResponse = await fetch(
        `https://restapi.amap.com/v3/weather/weatherInfo?key=${AMAP_KEY}&city=${city}&extensions=base`
      );
      const currentData = await currentResponse.json();
      
      if (currentData.status === '1' && currentData.lives && currentData.lives.length > 0) {
        state.currentWeather = currentData.lives[0];
      } else {
        throw new Error('未找到该城市的天气信息');
      }
      
      // 获取天气预报
      const forecastResponse = await fetch(
        `https://restapi.amap.com/v3/weather/weatherInfo?key=${AMAP_KEY}&city=${city}&extensions=all`
      );
      const forecastData = await forecastResponse.json();
      
      if (forecastData.status === '1' && forecastData.forecasts && forecastData.forecasts.length > 0) {
        state.forecastWeather = forecastData.forecasts[0].casts;
      }
      
    } catch (err) {
      console.error('获取天气失败:', err);
      state.error = '获取天气信息失败，请检查城市名称是否正确';
    } finally {
      state.loading = false;
    }
  };

  // 获取当前位置天气
  const getCurrentLocationWeather = async () => {
    if (!process.client) return;
    
    state.loading = true;
    state.error = null;
    
    try {
      // 使用浏览器定位API
      const position = await new Promise<GeolocationPosition>((resolve, reject) => {
        navigator.geolocation.getCurrentPosition(resolve, reject, {
          enableHighAccuracy: true,
          timeout: 10000,
          maximumAge: 60000
        });
      });
      
      const { longitude, latitude } = position.coords;
      
      // 根据坐标获取城市信息
      const cityResponse = await fetch(
        `https://restapi.amap.com/v3/geocode/regeo?key=${AMAP_KEY}&location=${longitude},${latitude}&output=json`
      );
      const cityData = await cityResponse.json();
      
      if (cityData.status === '1' && cityData.regeocode) {
        const city = cityData.regeocode.addressComponent.city || 
                     cityData.regeocode.addressComponent.district || 
                     cityData.regeocode.addressComponent.province;
        
        searchCity.value = city;
        await getWeatherByCity(city);
      } else {
        throw new Error('无法获取当前位置信息');
      }
      
    } catch (err) {
      console.error('获取位置天气失败:', err);
      state.error = '无法获取当前位置天气，请检查定位权限';
    } finally {
      state.loading = false;
    }
  };

  return {
    ...toRefs(state),
    searchCity,
    getWeatherIcon,
    getDayName,
    formatDate,
    searchWeather,
    getWeatherByCity,
    getCurrentLocationWeather
  };
}; 